<template>
	<view style="padding: 0 30rpx 30rpx;background-color: #fff;position: relative;">
		<view class="date">
			<text v-if="parentData.showDay" @click="chooseDate('day')" :class="{ active: timeFrame === 'day' }">日</text>
			<text @click="chooseDate('day7')" :class="{ active: timeFrame === 'day7' }">周</text>
			<text @click="chooseDate('month')" :class="{ active: timeFrame === 'month' }">月</text>
			<text @click="chooseDate('year')" :class="{ active: timeFrame === 'year' }">年</text>
		</view>
		<view style="overflow: hidden;">
			<picker mode="date" :value="$u.timeFormat(endTime, 'yyyy-mm-dd')" :start="startDate" :end="endDate"
				@change="bindDateChange" :fields="timeFrame==='day7'?'day':timeFrame">
				<!-- <view class="uni-input">{{date}}</view> -->
				<view style="float: left;width: 50%; text-align: right;" class="uni-input dateText"
					v-if="timeFrame === 'day'">
					{{$u.timeFormat(endTime, 'yyyy-mm-dd')}}
				</view>
				<view class="uni-input dateText" v-if="timeFrame === 'day7'">
					{{$u.timeFormat(startTime, 'yyyy-mm-dd')}}-{{$u.timeFormat(endTime, 'yyyy-mm-dd')}}
				</view>
				<view class="uni-input dateText" v-if="timeFrame === 'month'">
					{{$u.timeFormat(endTime, 'yyyy-mm')}}
				</view>
				<view class="uni-input dateText" v-if="timeFrame === 'year'">
					{{$u.timeFormat(endTime, 'yyyy')}}
				</view>
			</picker>
			<picker v-if="timeFrame === 'day'" mode="time" :value="time" @change="bindTimeChange">
				<view style="float: left;width: 50%; text-align: left;padding-left: 20rpx;" class="uni-input dateText">
					{{time}}
				</view>
			</picker>
		</view>

		<lechart ref="echarts2"></lechart>
	</view>
</template>

<script>
	// 条件编译引入小程序专用代码
	import lechart from "@/pages/chart/components/lime-echart/components/l-echart/l-echart.vue";
	import * as echarts from '../components/echarts.esm.min.js'
	import {
		getStatistics,
		historyPropert
	} from "../../../api/device/index.js";
	export default {
		props: {
			parentData: {
				type: JSON,
				required: true
			},
			setFuTime: {
				type: Function,
				required: true
			},
			gettongji: {
				type: Function,
				required: true
			},
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		components: {
			lechart,
		},
		data() {
			return {
				timeFrame: 'day7',
				time: '23:59',
				isMonthly: false,
				startTime: Date.parse(new Date(new Date().getTime() - 6 * 24 * 60 * 60 * 1000)),
				endTime: Date.parse(new Date()),
				chartType: 'bar',
			};
		},
		mounted() {
			// this.setFuTime(this.startTime, this.endTime,this.isMonthly,this.timeFrame)
			if (this.parentData.startTime) { //父传入开始结束时间
				this.startTime = this.parentData.startTime
				this.endTime = this.parentData.endTime
				this.chartType = 'line'
				this.Statistics()
			} else {
				if (this.parentData.showDay) {
					this.chooseDate('day')
				} else {
					this.setFuTime(this.startTime, this.endTime, this.isMonthly, this.timeFrame)
					this.Statistics()
				}
			}
		},
		methods: {
			bindDateChange: function(e) {
				let date = e.detail.value.split('-')
				this.setTime(date[0], date[1], date[2], this.timeFrame)
			},
			bindTimeChange: function(e) {
				this.time = e.detail.value
				let time = e.detail.value.split(":")
				let endTime = this.endTime
				this.startTime = new Date(this.$u.timeFormat(endTime, 'yyyy') * 1, this.$u.timeFormat(endTime, 'mm') -
					1, this.$u.timeFormat(endTime, 'dd') - 1, time[0] * 1, time[1] * 1, 0, 0).getTime();
				this.endTime = new Date(this.$u.timeFormat(endTime, 'yyyy') * 1, this.$u.timeFormat(endTime, 'mm') - 1,
					this.$u.timeFormat(endTime, 'dd'), time[0] * 1, time[1] * 1, 0, 0).getTime();
				this.setFuTime(this.startTime, this.endTime, this.isMonthly, this.timeFrame)
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			setTime(year, month, day, val) {
				if (val == 'day') {
					// 创建一个表示指定日期的 Date 对象
					this.startTime = new Date(year * 1, month * 1 - 1, day * 1, 0, 0, 0, 0).getTime();
					this.endTime = new Date(year * 1, month * 1 - 1, day * 1, 23, 59, 59, 999).getTime();
				}
				if (val == 'day7') {
					this.startTime = new Date(year * 1, month * 1 - 1, day * 1 - 6, 0, 0, 0, 0).getTime();
					this.endTime = new Date(year * 1, month * 1 - 1, day * 1, 23, 59, 59, 999).getTime();
				} else if (val == 'month') {
					this.startTime = new Date(year * 1, month * 1 - 1, 1, 0, 0, 0, 0).getTime();
					this.endTime = new Date(year * 1, month * 1, 0, 23, 59, 59, 999).getTime();
				} else if (val == 'year') {
					this.startTime = new Date(year * 1, 0, 1, 0, 0, 0, 0).getTime();
					this.endTime = new Date(year * 1, 11, 31, 23, 59, 59, 999).getTime();
				}
				this.setFuTime(this.startTime, this.endTime, this.isMonthly, this.timeFrame)
				this.Statistics()
			},
			chooseDate(val) {
				if (val == 'year') {
					this.isMonthly = true;
				} else {
					this.isMonthly = false;
				}
				if (val == 'day') {
					this.chartType = 'line'
				} else {
					this.chartType = 'bar'
				}
				this.timeFrame = val;
				const now = new Date();
				this.setTime(now.getFullYear(), now.getMonth() + 1, now.getDate(), val)
			},

			fatherLoad(obj) {
				//传给父级显示统计
				this.gettongji(obj);
				//父级历史
				this.setFuTime(this.startTime, this.endTime, this.isMonthly, this.timeFrame)
			},

			async Statistics() {
				let identifier = this.parentData.identifier.split(',') //父传入的identifier
				let name = this.parentData.name.split(','); //传入的词条的名字
				let color = this.parentData.color; //传入的词条的颜色
				let chartType = this.chartType //传入的chart的
				let ChartData = [] //BAR chart
				let Xdatas = [] //chartX轴
				let Ydatas = [] //line charty轴
				let Ymin = 0 //line charty轴
				let maxData = 0; //数据最大值
				if (this.parentData.identifier == 'spo2') {
					if (chartType == 'line') {
						Ymin = 100
					}
					if (chartType == 'bar') {
						Ymin = 60
					}
				}
				//chart数据
				let series = []
				let dayDate = [] //只要一条数据，就是上下限一样的
				if (chartType == 'line') {
					await historyPropert({
						startTime: this.startTime,
						endTime: this.endTime,
						current: 1,
						size: 100000,
						identifier: this.parentData.identifier
					}).then(res => {
						// let datas=dates
						if (res.obj.records.length == 0) {
							Xdatas.push(this.$u.timeFormat(this.startTime, 'mm-dd'))
							Ydatas.push(0)
						}
						
						res.obj.records.map(v => {
							if (this.parentData.identifier == 'spo2') {
								if (v.value * 1 > 100) {
									return false;
								}
								Ymin = v.value * 1 < Ymin ? v.value * 1 - 5 : Ymin
							}
							Xdatas.push(this.$u.timeFormat(v.time, 'hh:MM:ss'))
							if (this.parentData.identifier == '4000') { //4000舱内压力真实数据是/10d
								Ydatas.push(v.value / 10)
							} else {
								Ydatas.push(v.value * 1)
							}

						})
						let sortedGroups = [
							[{
								"dataType": this.parentData.identifier,
								"maxValue": Math.max(...Ydatas),
								"minValue": Math.min(...Ydatas),
							}]
						]
						this.fatherLoad(sortedGroups)
					})
					series = [{
						name: this.parentData.name,
						type: 'line',
						symbol: 'none',
						sampling: 'lttb',
						itemStyle: {
							color: color[0]
						},
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
									offset: 0,
									color: color[2]
								},
								{
									offset: 1,
									color: color[1]
								}
							])
						},
						data: Ydatas
					}]
				}
				if (chartType == 'bar') {
					// console.log(identifier);
					// for (const val of identifier) {

					// }
					let data = await getStatistics({
						identifier: this.parentData.identifier,
						isMonthly: this.isMonthly,
						startTime: this.startTime,
						endTime: this.endTime
					}).then(res => {
						// 将数据数组转换为 Map，以便快速查找
						let data = res.obj == null ? [] : res.obj;
						// 1. 按dataType分组
						const grouped = data.reduce((acc, item) => {
							const type = item.dataType;
							// 如果分组中没有该类型，初始化一个空数组
							if (!acc[type]) {
								acc[type] = [];
							}
							// 将当前项添加到对应分组
							acc[type].push(item);
							return acc;
						}, {});
						// 2. 按照指定顺序提取分组结果
						const sortedGroups = identifier.map(type => {
							// 如果有该类型的数据，返回对应的数组，否则返回空数组
							return grouped[type] || [];
						});
						this.fatherLoad(sortedGroups)
						// //传给父级显示统计
						// this.gettongji(sortedGroups);
						// //父级历史
						// this.setFuTime(this.startTime, this.endTime, this.isMonthly, this.timeFrame)
						sortedGroups.map(data => {
							let dataMap = new Map();
							data.map(item => {
								// data.forEach(item => {
								// });
								if (item.maxValue * 1 > maxData) {
									maxData = item.maxValue
								}
								let date = ''
								if (this.isMonthly) {
									date = new Date(item.month).getTime()
								} else {
									date = new Date(item.day).getTime()
								}
								dataMap.set(date, {
									minValue: item.minValue,
									maxValue: item.maxValue
								});

							})
							// 定义目标日期范围（假设从某个起始日期到结束日期）
							let startTime = this.startTime; // 起始时间戳
							let endTime = this.endTime; // 结束时间戳
							// 初始化结果数组
							let minValues = [];
							let maxValues = [];
							let dates = [];
							// 遍历目标日期范围
							let currentDate = new Date(startTime);
							let endDate = new Date(endTime);
							while (currentDate <= endDate) {
								let formattedDate;
								if (this.timeFrame == 'year') {
									formattedDate = this.$u.timeFormat(currentDate, 'mm');
								} else {
									formattedDate = this.$u.timeFormat(currentDate,
										'mm/dd');
								}
								dates.push(formattedDate);
								// 获取当前日期的时间戳（以天为单位，通常将时间部分设置为 00:00:00）
								let currentDateTimestamp = new Date(currentDate
									.getFullYear(),
									currentDate
									.getMonth(),
									currentDate.getDate()).getTime();
								// 检查当前日期是否在数据中存在
								if (dataMap.has(currentDateTimestamp)) {
									let {
										minValue,
										maxValue
									} = dataMap.get(currentDateTimestamp);
									minValues.push(minValue * 1);
									maxValues.push(maxValue * 1 - minValue * 1);
								} else {
									// 如果不存在，推入空值
									minValues.push(0); // 或者使用 ''，根据需要
									maxValues.push(0); // 或者使用 ''，根据需要
								}
								// 将当前日期增加一天
								if (this.timeFrame == 'year') {
									currentDate.setMonth(currentDate.getMonth() + 1);
								} else {
									currentDate.setDate(currentDate.getDate() + 1);
								}
							}
							ChartData.push({
								dates,
								minValues,
								maxValues
							})
						})
					});
					ChartData.map((val, index) => {
						let scatterData = {
							symbolSize: 5,
							data: [],
							itemStyle: {
								color: color[index]
							},
							type: 'scatter'
						}
						val.minValues.map((minval, index) => {
							if (minval > 0) { //因为上下限一样为了能在图上显示出形状进行修改，下限减去数据最大值的4%
								val.minValues[index] = val.minValues[index] - maxData * 0.04
								val.maxValues[index] = val.maxValues[index] + maxData * 0.04
								dayDate.push(ChartData[0].dates[index]) //得到修改的日期
							}
						})
						// series.push(scatterData)
						series.push({
							name: name[index],
							type: 'bar',
							stack: 'Total' + index,
							itemStyle: {
								borderColor: 'transparent',
								color: 'transparent'
							},
							emphasis: {
								itemStyle: {
									borderColor: 'transparent',
									color: 'transparent'
								}
							},
							data: val.minValues,
							barMaxWidth: 10,
						}, {
							name: name[index],
							type: 'bar',
							stack: 'Total' + index,
							itemStyle: {
								borderRadius: 5,
								color: color[index]
							},
							data: val.maxValues,
							barMaxWidth: 10,
						})
					})
					if (ChartData.length > 0) {
						Xdatas = ChartData[0].dates; //图标x轴
					}

				}
				// 指定图表的配置项和数据
				let dataZoomlength = 100;
				if (Xdatas.length > 13 && Xdatas.length < 20) {
					dataZoomlength = 60
				}
				if (Xdatas.length > 20) {
					dataZoomlength = 30
				}
				const option = {
					title: {
						show: false,
					},
					tooltip: {
						trigger: 'axis',
						confine: true,
						axisPointer: {
							type: 'shadow'
						},
						position: function(pt) {
							return [pt[0], '10%'];
						},
						formatter: function(params) {
							let formatter = '';
							if (chartType == 'bar') {
								params = params.filter(item => item.componentSubType === "bar")
								for (let i = 0; i < params.length / 2; i++) {
									var min = params[i * 2];
									var max = params[i * 2 + 1];
									if (min.value > 0) {
										min.value = min.value + maxData * 0.04 //因为上下限一样为了能在图上显示出形状进行修改，显示修改回来
									}
									if (max.value > 0) {
										max.value = max.value - maxData * 0.04
									}
									let axisValue = min.axisValue;
									let maxValue = max.value + min.value;
									dayDate = [...new Set(dayDate)]
									let isDayDate = false;
									dayDate.map(val => {
										if (val == axisValue) {
											formatter += min.name + ' : ' + min.seriesName +
												'\n' + min.value + ' - ' + maxValue
											if (i != params.length / 2 - 1) {
												formatter += '\n'
											}
											isDayDate = true;
										}
									})
									if (!isDayDate) {
										formatter += min.name + ' : ' + min.seriesName +
											'\n' + min.value + ' - ' + maxValue
										if (i != params.length / 2 - 1) {
											formatter += '\n'
										}
									}
								}
							}
							if (chartType == 'line') {
								formatter += params[0].name + ' : ' + params[0].seriesName +
									'\n' + params[0].value
							}
							return formatter
						}
					},
					grid: {
						left: '0%',
						right: '0%',
						top: '4%',
						bottom: '15%',
						containLabel: true
					},
					xAxis: {
						type: 'category',
						splitLine: {
							show: false
						},
						data: Xdatas
					},
					yAxis: {
						type: 'value',
						min: Ymin,
					},
					dataZoom: [{
						type: 'slider',
						show: true,
						start: 0,
						end: dataZoomlength,
						xAxisIndex: [0]
					}],
					series: series
				};
				// 使用刚指定的配置项和数据显示图表
				this.$refs.echarts2.init(echarts, chart => {
					chart.setOption(option);
				});
			},
		}
	}
</script>
<style lang="scss">
	.date {
		text-align: center;

		text {
			display: inline-block;
			width: 50rpx;
			text-align: center;
			line-height: 64rpx;
			margin: 15rpx;
		}

		text.active {
			color: #fa5d0b;
			border-bottom: 1px solid #fa5d0b;
		}
	}

	.dateText {
		text-align: center;
		font-size: 12px;
		line-height: 60rpx;
	}
</style>